import { _decorator, Component, EventTarget, EventTouch, input, Node, NodeEventType, UITransform, Vec2 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('UICom_GameInput')
export class UICom_Joystick extends Component {

    public On: (dir: Vec2) => void = null;

    private readonly _startPos: Vec2 = new Vec2();
    private readonly _lastPos: Vec2 = new Vec2();
    private readonly _dir: Vec2 = new Vec2();

    private _touchID: number = -1;

    start() {
        this.node.on(Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.on(Node.EventType.TOUCH_CANCEL, this.onTouchCancel, this);
    }

    protected onDestroy(): void {
        this.node.off(Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.off(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.node.off(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.off(Node.EventType.TOUCH_CANCEL, this.onTouchCancel, this);
    }

    update(deltaTime: number) {
        if (-1 != this._touchID) {
            if (null != this.On) {
                this._dir.x = this._lastPos.x - this._startPos.x;
                this._dir.y = this._lastPos.y - this._startPos.y;
                this.On(this._dir.normalize());
            }
        }
    }

    protected onTouchStart(e: EventTouch) {
        if (-1 != this._touchID) return;
        this._touchID = e.getID();

        let pos = e.getUILocation();

        this._startPos.x = pos.x;
        this._startPos.y = pos.y;

        this._lastPos.x = pos.x;
        this._lastPos.y = pos.y;
    }

    protected onTouchMove(e: EventTouch) {
        if (this._touchID != e.getID()) {
            return;
        }
        let pos = e.getUILocation();

        this._lastPos.x = pos.x;
        this._lastPos.y = pos.y;
    }

    protected onTouchEnd(e: EventTouch) {
        if (this._touchID != e.getID()) {
            return;
        }
        this._touchID = -1;
    }

    protected onTouchCancel(e: EventTouch) {
        if (this._touchID != e.getID()) {
            return;
        }
        this._touchID = -1;
    }
}

